package F21AS_Freddy.AFJ_Taxikiosk.src;

import java.util.Observable;
import java.util.Random;

/**
 * This class used to process passengers in queue.
 * @author Freddy Wong
 * F21AS Course Work Stage2 @ Year 2015
 */

public class Kiosk extends Observable implements Runnable {

	private static final String REPORT_FILE = "Report.txt";
	private final static int KIOSK_BUSY_TIMER = 2700;

	private Passenger passenger;
	private Queue queue;
	private Boolean isOpen;
	private PassengerList passengerList;

	public Kiosk(Queue queue, PassengerList passengerList) {
		this.passengerList = passengerList;
		this.queue = queue;
		isOpen = false;

	}

	/**
	 * Processes a queue of passengers, assesses baggage and levies charges as
	 * necessary. Once processed the passengers are added to the passenger list.
	 * 
	 * @param queue
	 *            Queue of passengers and baggage to be processed
	 * @param passengerList
	 *            Empty to be populated with processed passengers
	 */
	public void processQueue() {
		Random random = new Random();
		while (isOpen) {

			synchronized (queue) {

				while (queue.getIsEmpty()) {
					try {
						passenger = null;
						this.setChanged();
						this.notifyObservers();
						queue.wait(500);

					} catch (InterruptedException e) {
						String error = "Error calling wait method of the queue thread in DropOffDesk: " + e.getStackTrace();
						System.out.println(error);
					}

				}

				passenger = queue.removeFirst();
				processPassenger();
			}

			try {
				Thread.sleep(random.nextInt(KIOSK_BUSY_TIMER));
			} catch (InterruptedException e) {
				String error = "DropOffDesk exception raised sleeping thread: "	+ e.getStackTrace();
				System.out.println(error);
			}

		}

	}

	/*
	 * Private method to process the baggage of a passenger and add them to the
	 * PassengerList
	 */
	private void processPassenger() {

		passengerList.add(passenger);
		this.setChanged();
		this.notifyObservers();
	}

	public Passenger getCurrentPassenger() {
		return passenger;
	}

	public Boolean getIsOpen() {
		return isOpen;
	}

	public synchronized void setIsOpen(Boolean kioskIsOpen) {

			if (kioskIsOpen != isOpen) {
				
				if (!kioskIsOpen) {
					/*
					 * if the Kiosk Is Close, write to files
					 */
					passengerList.writeToFile(REPORT_FILE);
					
				} 
				
				this.isOpen = kioskIsOpen;
				setChanged();
				notifyObservers();
			}
		
	}

	@Override
	public void run() {
		processQueue();

	}

} // End of Kiosk Class